import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getUserMenus as getUserMenusAPI, getUserPermissions as getUserPermissionsAPI } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const usePermissionStore = defineStore('permission', () => {
  const menus = ref([])
  const permissions = ref([])
  const routes = ref([])

  // 获取用户菜单
  const getUserMenus = async () => {
    try {
      const response = await getUserMenusAPI()
      menus.value = response.data.menus || []
      return response
    } catch (error) {
      ElMessage.error('获取用户菜单失败')
      throw error
    }
  }

  // 获取用户权限
  const getUserPermissions = async () => {
    try {
      const response = await getUserPermissionsAPI()
      permissions.value = response.data.permissions || []
      return response
    } catch (error) {
      ElMessage.error('获取用户权限失败')
      throw error
    }
  }

  // 检查是否有权限
  const hasPermission = (permissionCode) => {
    if (!permissionCode) return true
    return permissions.value.includes(permissionCode)
  }

  // 检查是否有角色
  const hasRole = (roleCode) => {
    if (!roleCode) return true
    // 这里需要从用户信息中获取角色
    return true
  }

  // 生成路由
  const generateRoutes = (menus) => {
    const routes = []
    
    const generateRoute = (menu) => {
      const route = {
        path: menu.path,
        name: menu.name,
        component: menu.component ? () => import(`@/views/${menu.component}.vue`) : null,
        meta: {
          title: menu.title,
          icon: menu.icon,
          hidden: menu.hidden,
          permission: menu.permission
        }
      }
      
      if (menu.children && menu.children.length > 0) {
        route.children = menu.children.map(child => generateRoute(child))
      }
      
      return route
    }
    
    menus.forEach(menu => {
      routes.push(generateRoute(menu))
    })
    
    return routes
  }

  // 设置菜单
  const setMenus = (menuList) => {
    menus.value = menuList
  }

  // 设置权限
  const setPermissions = (permissionList) => {
    permissions.value = permissionList
  }

  // 设置路由
  const setRoutes = (routeList) => {
    routes.value = routeList
  }

  // 清除权限数据
  const clearPermissions = () => {
    menus.value = []
    permissions.value = []
    routes.value = []
  }

  return {
    menus,
    permissions,
    routes,
    getUserMenus,
    getUserPermissions,
    hasPermission,
    hasRole,
    generateRoutes,
    setMenus,
    setPermissions,
    setRoutes,
    clearPermissions
  }
}) 